﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Search.WebControls;
using Microsoft.Office.Server.Search.Query;
using System.Xml.XPath;

namespace MS.InformationManagement.Controls.Webparts.SortedSearchResults
{
    [ToolboxItemAttribute(false)]
    public class SortedSearchWebPart : CoreResultsWebPart
    {

        protected override void CreateDataSource()
        {
            this.DataSource = new MyCoreResultsDataSource(this);
        }


        public class MyCoreResultsDataSource : CoreResultsDatasource
        {
            public MyCoreResultsDataSource(CoreResultsWebPart ParentWebpart)
                : base(ParentWebpart)
            {

                //create the View that will be used with this datasource
                this.View = new MyCoreResultsDataSourceView(this, "MyCoreResults");
            }

        }

        public class MyCoreResultsDataSourceView : CoreResultsDatasourceView
        {

            public MyCoreResultsDataSourceView(SearchResultsBaseDatasource DataSourceOwner, string ViewName)
                : base(DataSourceOwner, ViewName)
            {

                if (DataSourceOwner == null)
                {
                    throw new ArgumentNullException("DataSourceOwner");
                }

                MyCoreResultsDataSource ds = this.DataSourceOwner as MyCoreResultsDataSource;
                this.QueryManager = SharedQueryManager.GetInstance(ds.ParentWebpart.Page).QueryManager;

            }

            public override void AddSortOrder(SharePointSearchRuntime runtime)
            {

                if (runtime.KeywordQueryObject == null)
                {
                    return;
                }

                runtime.KeywordQueryObject.SortList.Clear();
                SortedSearchWebPart wp = this.DataSourceOwner.ParentWebpart as SortedSearchWebPart;
                string sortField = (string)wp.Page.Request["f"];
                string sortOrder = (string)wp.Page.Request["o"];

                if (!string.IsNullOrEmpty(sortField))
                {
                    /*
                    SortDirection dir = (sortOrder == "ASC") ? SortDirection.Ascending : SortDirection.Descending;
                    runtime.KeywordQueryObject.SortList.Add(sortField, dir);*/
                }
                else
                    base.AddSortOrder(runtime);
            }
        }
    }
}
